﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebSite.Areas.WebApi.Controllers;
using System.Text;
using WebSite.Models;
using HyEduOnline.Server.Admin;
using HyEduOnline.Server.Teacher;
using HyEudOnline.Server.Common;
using HyEduOnline.Entities;
using HyEduOnline.Data;
using System.Data;

using HyEduOnline.Models;
using HyEduOnline.Server.Common;
namespace WebSite.Areas.WebApi.Controllers
{
    public class SysUserController : SysUserBaseController
    {

        private const int StudentType = 0;
        private const int TeacherType = 1;
        private const int MangerType = 2;
        private const int AllType = 3;
        private SysUserDAO suDao = new SysUserDAO();
        private SysRoleDAO srDao = new SysRoleDAO();
        private SyspartDAO syspartDAO = new SyspartDAO();
        private SysUserRoleDAO sysUserRoleDao = new SysUserRoleDAO();


        #region 登录验证
        public int SysUser(string UserName, string PassWord)
        {
            if ((!string.IsNullOrEmpty(UserName)) && (!string.IsNullOrEmpty(PassWord)))
            {
                SetCookie(UserName, PassWord, MangerType);

                PassWord = Utitil.MD5(PassWord);//加密

                if (ValidateSysUser(UserName, PassWord))
                {

                    return 1;//登陆成功
                }

                return 0;
            }
            else
            {
                return -3;
            }
        }


        private void SetCookie(string UserName, string PassWord, int UserType)
        {
            string passWord = encryption.XOR(PassWord);//密码加密

            HttpCookie cookie = new HttpCookie("User");
            cookie.Values["LoginName"] = UserName;
            cookie.Values["LoginPassWord"] = passWord;
            cookie.Values["UserType"] = UserType.ToString();
            cookie.Expires = System.DateTime.Now.AddDays(3);//设置过期时间3天
            Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 系统用户的验证
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="Password">MD5口令</param>
        /// <returns></returns>
        private bool ValidateSysUser(string UserName, string Password)
        {
            string WhereClause = "S_UserName ='" + UserName + "' and  S_Password='" + Password + "' ";

            //LogWrite logWrite = new LogWrite();

            int count = 0;
            IList<TbSysUser> tmpItems = suDao.getByPageDataBase(0, 1, "ID ASC", WhereClause, out count);
            if (tmpItems.Count > 0)
            {
                TbSysUser item = tmpItems[0];//取第一个用户               

                Session["UserID"] = item.Id;//用户id,
                Session["UserName"] = item.SUserName;//用户名
                Session["TrueName"] = item.STrueName;//用户真名
                Session["UserType"] = MangerType;//管理员类型
                Session["PartID"] = item.IPart;//用户所在部门ID;
                if (!string.IsNullOrEmpty(item.SImg))
                {
                    Session["SysHeader"] = item.SImg;
                }
                else
                {
                    Session["SysHeader"] = "/Images/headpic.png";//使用默认图片
                }
                //(2)根据id，取用户的角色

                IList<TbSysUserRole> tmpUserRoles = new SysUserRoleDAO().findByIUserid(item.Id);

                string strRoleName = "", strRoleID = "", strPowerList = "";//角色列表，权限列表

                //IList<string> powerList = new List<string>();
                foreach (var itemR in tmpUserRoles)
                {
                    string tmpStrR = "";
                    TbSysRole tmpRole = srDao.GetByID((int)itemR.IRoleId);

                    if (tmpRole != null)
                    {
                        tmpStrR = tmpRole.SPower;
                        if (!string.IsNullOrEmpty(tmpStrR))
                        {                          
                            strPowerList += tmpStrR + ",";//保存该用户的所有权限
                        }

                        strRoleName += tmpRole.SRoleName + ",";
                        strRoleID += itemR.IRoleId + ",";//保存该用户的所有角色
                    }


                }

                //由于多个角色的权限表可能相同，所以需要合并
                //foreach (string itemUR in powerList)
                //{

                //    strPowerList = Utitil.UnionStr(strPowerList, itemUR);//权限列表，需要合并

                //}

                strPowerList = Utitil.clearRsplit(strPowerList, ',');//清除无效的,号

                Session["RoleName"] = strRoleName;
                Session["RoleID"] = strRoleID;
                Session["PowerList"] = strPowerList;

                //再接下来，读对应的权限表，并放放到session中
                IList<TbSysPagePower> spLists = new SysPagePowerDAO().finByIds(strPowerList);
                if (spLists.Count > 0)
                {
                    //接下来进行节点组装

                    HyEduOnline.Server.Common.ComTreeNode root = new HyEduOnline.Server.Common.ComTreeNode();
                    root.NodeName = "根结点";
                    Dictionary<int, HyEduOnline.Server.Common.ComTreeNode> nodeslist = new Dictionary<int, HyEduOnline.Server.Common.ComTreeNode>();
                    foreach (var itemPower in spLists)
                    {
                        HyEduOnline.Server.Common.ComTreeNode myNode = new HyEduOnline.Server.Common.ComTreeNode();
                        HyEduOnline.Server.Common.ComTreeNode tempNode;
                        myNode.NodeName = itemPower.SMenuName;

                        myNode.Id = itemPower.Id;
                        myNode.Url = itemPower.SMenuUrl;
                        myNode.Tip = itemPower.SPicurl;

                        nodeslist.Add(itemPower.Id, myNode);

                        if (Convert.ToInt32(itemPower.IParentId) != 0)
                        {
                            tempNode = (HyEduOnline.Server.Common.ComTreeNode)nodeslist[(int)itemPower.IParentId];

                            tempNode.Childrens.Add(myNode);
                        }
                        else
                        {
                            root.Childrens.Add(myNode);
                        }

                    }

                    Session["SysMenus"] = root;

                }


                // logWrite.WriteInLogInfo(LogType.LoginSuccess);
                //得到登录IP与最后登录时间
                item.SLip = Utitil.getIP();
                item.DJoinTime = DateTime.Now;
                //更新信息
                suDao.Update(item);
                return true;

            }
            else
            {
                //logWrite.WriteInLogInfo(LogType.LoginFailure);
                return false;
            }

        }

        #endregion

        /// <summary>
        /// 验证用户名唯一
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public JsonResult UserNameValidate(string UserName)
        {
            List<TbSysUser> list = SysUserDAO.GetByPage("S_UserName = '" + UserName + "'", 0, 20).ToList();

            return Json(list, JsonRequestBehavior.AllowGet);
        }


        #region 从user和part中获取数据,分页，筛选
        /// <summary>
        /// 从user和part中获取数据
        /// </summary>
        /// <param name="firstResult"></param>
        /// <param name="pagesize"></param>
        /// <param name="orderBy"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public JsonResult GetByPageUserAndUserRole(int firstResult, int pagesize, string orderBy, string condition)
        {
            int count = 0;
            condition = HttpUtility.UrlDecode(condition);//对条件解码
            List<UserAndUserRole> Data = new List<UserAndUserRole>();//user加上部门名称的模型集合
            //获取当前页的user；
            List<TbSysUser> userList = suDao.getByPageDataBase(firstResult, pagesize, "ID", condition, out count).ToList();
            foreach (TbSysUser item in userList)
            {
                UserAndUserRole tmpChildren = new UserAndUserRole();
                string SPartName = "";
                //为每个user加上部门名称
                if (!string.IsNullOrEmpty(item.IPart.ToString()))
                {
                    int partId = (int)item.IPart;
                    if (partId != 0)
                    {
                        SPartName = syspartDAO.GetByID(partId).SPartName;
                        tmpChildren.SPartName = SPartName;
                    }
                    else
                        tmpChildren.SPartName = "";
                }
                string[] list = { "SPassword" };

                ClassValueCopier.Copy(tmpChildren, item);

                //置空密码，不传送到客户端
                tmpChildren.SPassword = "";

                Data.Add(tmpChildren);
            }

            return Json(new
            {
                DataCount = count,
                Data = Data,
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 同时对两张表进行删除，user和userRole;
        /// <summary>
        /// 同时对两张表进行删除，user和userRole;
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public int DeleteUserAndUserRole(string ids)
        {
            try
            {
                int count = 0;
                string[] SIds = ids.Split(new char[] { ',' });

                foreach (string SId in SIds)
                {
                    int IId = int.Parse(SId);//User的id;
                    //查找目标user拥有角色
                    List<TbSysUserRole> list = sysUserRoleDao.GetByPage("I_userid =" + IId, 0, 20, "ID", "DESC", out count).ToList();

                    foreach (var i in list)
                    {
                        sysUserRoleDao.Del(i.Id);//逐个角色删除
                    }

                    SysUserDAO.Del(IId);//删除user
                }
                return 1;
            }
            catch (Exception ex)
            {

                return 0;
            }
        }
        #endregion

        #region 获取当前Id用户的数据
        /// <summary>
        /// 从userRoleVW视图中返回指定ID的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult GetUserAndUserRole(int id)
        {
            TbSysUser user = suDao.GetByID(id);//获取当前用户
            UserAndUserRole item = new UserAndUserRole();
            if (!string.IsNullOrEmpty(item.IPart.ToString()))
            {
                string SPartName = "";
                int partId = (int)item.IPart;
                SPartName = syspartDAO.GetByID(partId).SPartName;
                item.SPartName = SPartName;//将部门加上
            }
            ClassValueCopier.Copy(item, user);

            //置空密码，不传送到客户端
            item.SPassword = "";

            return Json(item, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 同时对user和userRole进行添加
        /// <summary>
        /// 同时对user和userRole进行添加
        /// </summary>
        /// <param name="item1"></param>
        /// <param name="RoleIds"></param>
        /// <returns></returns>
        public int AddUserAndUserRole(TbSysUser User, string RoleIds)
        {

            try
            {
                string[] IRoleIds;
                string SRoleName = "";
                IRoleIds = RoleIds.Split(new char[] { ',' });//拆分角色Id；
                TbSysUserRole UserRole = new TbSysUserRole();//userRole添加的对象
                foreach (string id in IRoleIds)
                {
                    UserRole.IRoleId = int.Parse(id);
                    SRoleName = srDao.GetByID(int.Parse(id)).SRoleName + "," + SRoleName;
                }
                SRoleName = SRoleName.Substring(0, SRoleName.Length - 1);
                User.STmp1 = SRoleName;

                User.SPassword = Utitil.MD5(User.SPassword);//密码加密 by lx 2015.1.20

                if (!suDao.Insert(User))
                    return 0;//用户添加失败，直接退出函数
                UserRole.IUserid = User.Id;
                foreach (string id in IRoleIds)
                {
                    UserRole.IRoleId = int.Parse(id);
                    if (!sysUserRoleDao.Insert(UserRole)) return 0;//添加失败
                }
                return 0;
            }
            catch (Exception ex)
            {

                return 0;
            }
        }
        #endregion

        #region 更新操作，对user和userRole
        /// <summary>
        /// 更新操作，对user和userRole
        /// </summary>
        /// <param name="item"></param>
        /// <param name="id"></param>
        /// <param name="RoleIds"></param>
        /// <returns></returns>
        public int PutUserAndUserRole(TbSysUser item, string RoleIds)
        {

            try
            {
                if (!string.IsNullOrEmpty(RoleIds))
                {
                    string[] IRoleIds;
                    string SRoleName = "";
                    IRoleIds = RoleIds.Split(new char[] { ',' });//拆分角色Id；
                    TbSysUserRole UserRole = new TbSysUserRole();//userRole添加的对象
                    UserRole.IUserid = item.Id;
                    //删除user旧的角色
                    TList<TbSysUserRole> OldUserRole = sysUserRoleDao.GetByPage("I_userid =" + item.Id, 0, int.MaxValue);
                    sysUserRoleDao.Del(OldUserRole);
                    //添加user新的角色
                    foreach (string id in IRoleIds)
                    {
                        UserRole.IRoleId = int.Parse(id);
                        SRoleName = srDao.GetByID(int.Parse(id)).SRoleName + "," + SRoleName;//拼装角色字符串
                        if (!sysUserRoleDao.Insert(UserRole)) return 0;//添加失败
                    }
                    SRoleName = SRoleName.Substring(0, SRoleName.Length - 1);
                    item.STmp1 = SRoleName;
                }
                //判断是否更新密码 by lx 2015.1.21
                if (!string.IsNullOrEmpty(item.SPassword))
                {
                    //更新密码
                    item.SPassword = Utitil.MD5(item.SPassword);//加密
                    suDao.Update(item);//更新
                }
                else
                {//不更新密码
                    TbSysUser newItem = suDao.GetByID(item.Id);
                    item.SPassword = newItem.SPassword;//原密码
                    suDao.Update(item);//更新
                }
                
                return 1;
            }
            catch (Exception ex)
            {
                return 0;
            }
        } 
        #endregion

        #region 对DeanOpenCourse和TeaOpenCourse添加操作
        /// <summary>
        /// 添加学期开课表，同时记录教师的上课表,对DeanOpenCourse和TeaOpenCourse操作
        /// </summary>
        /// <param name="item"></param>
        /// <param name="sCourseCode"></param>
        /// <returns></returns>
        public int AddOpenCourse(TbDeanOpenCourse item, string sCourseCode)
        {
            try
            {
                new DeanOpenCourseDAO().Insert(item);//将新数据插入DeanOpenCourse表
                TeaOpenCourseDAO teaOpenCourseDao = new TeaOpenCourseDAO();
                //判断TeaOpenCourse中是否存在该字段，决定是否插入新的数据
                string whereClase = "S_CourseCode = '" + sCourseCode + "' and S_TeacherCode ='" + item.STeacharCode + "'";
                TList<TbTeaOpenCourse> teaOpenList = teaOpenCourseDao.GetByPage(whereClase, 0, int.MaxValue);
                if (teaOpenList.Count == 0)//没有该字段，先赋值再插入
                {
                    TbTeaOpenCourse teaOpen = new TbTeaOpenCourse();
                    teaOpen.ICourseId = item.ICourseId;
                    teaOpen.SCourseCode = sCourseCode;
                    teaOpen.SCourseName = item.SCourseName;
                    teaOpen.STeacherCode = item.STeacharCode;
                    teaOpen.STeacherName = item.STeacharName;
                    //赋值完成后，插入
                    teaOpenCourseDao.Insert(teaOpen);
                }
                return 1;
            }
            catch (Exception e)
            {

                return 0;
            }
        }
        #endregion

        #region 对DeanOpenCourse和TeaOpenCourse修改操作
        /// <summary>
        /// 修改时，根据条件判断
        /// </summary>
        /// <param name="item"></param>
        /// <param name="sCourseCode"></param>
        /// <returns></returns>
        public int UpdateOpenCourse(TbDeanOpenCourse item, string sCourseCode)
        {
            new DeanOpenCourseDAO().Update(item);//更新DeanOpenCourse中的数据
            if (sCourseCode == "")
                return 1;
            else
            {
                TeaOpenCourseDAO teaOpenCourseDao = new TeaOpenCourseDAO();
                //判断TeaOpenCourse中是否存在该字段，决定是否插入新的数据
                string whereClase = "S_CourseCode = '" + sCourseCode + "' and S_TeacherCode ='" + item.STeacharCode + "'";
                TList<TbTeaOpenCourse> teaOpenList = teaOpenCourseDao.GetByPage(whereClase, 0, int.MaxValue);
                if (teaOpenList.Count == 0)//没有该字段，先赋值再插入
                {
                    TbTeaOpenCourse teaOpen = new TbTeaOpenCourse();
                    teaOpen.ICourseId = item.ICourseId;
                    teaOpen.SCourseCode = sCourseCode;
                    teaOpen.SCourseName = item.SCourseName;
                    teaOpen.STeacherCode = item.STeacharCode;
                    teaOpen.STeacherName = item.STeacharName;
                    //赋值完成后，插入
                    teaOpenCourseDao.Insert(teaOpen);
                }
            }
            return 1;
        }
        #endregion
       // Test11.14
        //首页写判断出错
        /// <summary>
        /// 首页获取公告,邮箱
        /// </summary>
        /// <returns></returns>
        public JsonResult Search()
        {
            int totalCount = 0;  //总的数据记录条数I_NoticesType
            string condition = "1 = 1";
            IList<TbNotices> noticeList = new NoticesDAO().GetByPage(condition, 0, 5, "DSendTime", "DESC", out totalCount);
            condition = "I_IsRead=0 and S_RecNo='" + FrontUserInfo.GetSysUserName() + "'";
            IList<VwEmail> emailList = new VwEmailDAO().GetByPageVW(condition, 0, 5, "DSendTime DESC", out totalCount);
            return Json(
                new
                {
                    noRead = totalCount,
                    notices = noticeList,
                    emails = emailList
                });
        }


    }
}
